/**
 * @file class.js
 * @description 班级管理路由
 * @created 2024-07-01
 */

import express from 'express'
import mysql from 'mysql'
import { dbConfig } from '../config/database.js'

const router = express.Router()

// 创建数据库连接池
const pool = mysql.createPool(dbConfig)

/**
 * 获取班级列表
 * @route GET /admin/class/list
 */
router.get('/admin/class/list', async (req, res) => {
  try {
    pool.query(
      `SELECT 
        c.id, c.class_code as classCode, c.name, c.grade_year as gradeYear,
        c.department_id as departmentId, c.college_id as collegeId,
        c.status, c.create_time as createTime,
        col.name as collegeName
      FROM yzh_classes c
      LEFT JOIN yzh_colleges col ON c.college_id = col.id
      WHERE c.status = 1
      ORDER BY c.id ASC`,
      (err, results) => {
        if (err) {
          console.error('获取班级列表失败:', err)
          return res.status(500).json({
            code: 500,
            message: '获取班级列表失败',
            error: err.message
          })
        }
        
        return res.json({
          code: 200,
          message: '获取班级列表成功',
          data: results
        })
      }
    )
  } catch (error) {
    console.error('获取班级列表失败:', error)
    return res.status(500).json({
      code: 500,
      message: '获取班级列表失败',
      error: error.message
    })
  }
})

/**
 * 获取班级详情
 * @route GET /admin/class/detail/:id
 */
router.get('/admin/class/detail/:id', async (req, res) => {
  try {
    const classId = req.params.id
    
    pool.query(
      `SELECT 
        c.id, c.class_code as classCode, c.name, c.grade_year as gradeYear,
        c.department_id as departmentId, c.college_id as collegeId,
        c.status, c.create_time as createTime,
        col.name as collegeName
      FROM yzh_classes c
      LEFT JOIN yzh_colleges col ON c.college_id = col.id
      WHERE c.id = ?`,
      [classId],
      (err, results) => {
        if (err) {
          console.error('获取班级详情失败:', err)
          return res.status(500).json({
            code: 500,
            message: '获取班级详情失败',
            error: err.message
          })
        }
        
        if (results.length === 0) {
          return res.status(404).json({
            code: 404,
            message: '班级不存在'
          })
        }
        
        return res.json({
          code: 200,
          message: '获取班级详情成功',
          data: results[0]
        })
      }
    )
  } catch (error) {
    console.error('获取班级详情失败:', error)
    return res.status(500).json({
      code: 500,
      message: '获取班级详情失败',
      error: error.message
    })
  }
})

// 获取班级学生列表
// GET /api/class/:classId/students
router.get('/class/:classId/students', (req, res) => {
  const { classId } = req.params
  console.log(`处理班级(ID: ${classId})学生列表请求`)
  
  // 生成模拟数据
  const students = generateMockStudents(classId, 30)
  
  // 直接返回结果
  res.json(students)
})

// 根据学院/年级/班级ID获取班级详情
// GET /api/colleges/:collegeId/grades/:gradeId/classes/:classId
router.get('/colleges/:collegeId/grades/:gradeId/classes/:classId', (req, res) => {
  const { collegeId, gradeId, classId } = req.params
  console.log(`处理班级详情请求: collegeId=${collegeId}, gradeId=${gradeId}, classId=${classId}`)
  
  // 获取学院名称
  const collegeName = getCollegeName(collegeId)
  
  // 获取专业名称
  const majorName = getMajorName(collegeId, classId)
  
  // 生成班级详情
  const classInfo = {
    name: `${majorName}${gradeId}班`,
    college: collegeName,
    grade: `${gradeId}级`,
    studentCount: 30,
    courseCount: Math.floor(Math.random() * 5) + 5,
    avgScore: Math.floor(Math.random() * 10) + 80,
    ranking: Math.floor(Math.random() * 10) + 1,
    teacherName: getRandomTeacherName()
  }
  
  // 直接返回结果
  res.json(classInfo)
})

// 获取学院名称
function getCollegeName(collegeId) {
  const colleges = {
    '1': '计算机科学与技术学院',
    '2': '经济与金融学院',
    '3': '电子信息工程学院',
    '4': '医学院',
    '5': '法学院',
    '6': '外国语学院'
  }
  
  return colleges[collegeId] || '未知学院'
}

// 获取专业名称
function getMajorName(collegeId, classId) {
  const majors = {
    '1': ['计算机科学与技术', '软件工程', '人工智能', '数据科学'],
    '2': ['金融学', '经济学', '国际贸易', '会计学'],
    '3': ['电子信息工程', '通信工程', '自动化', '物联网工程'],
    '4': ['临床医学', '口腔医学', '药学', '护理学'],
    '5': ['法学', '知识产权', '国际法', '刑法'],
    '6': ['英语', '日语', '法语', '德语']
  }
  
  const collegeValid = majors.hasOwnProperty(collegeId)
  const majorIndex = classId % 4
  
  if (!collegeValid) {
    return '未知专业'
  }
  
  return majors[collegeId][majorIndex]
}

// 获取随机教师姓名
function getRandomTeacherName() {
  const surnames = ['张', '王', '李', '赵', '陈', '刘', '杨', '黄', '周', '吴']
  const names = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '洋', '艳']
  
  const surname = surnames[Math.floor(Math.random() * surnames.length)]
  const name = names[Math.floor(Math.random() * names.length)]
  
  return surname + name
}

// 生成模拟学生数据
function generateMockStudents(classId, count = 30) {
  const students = []
  const surnames = ['张', '王', '李', '赵', '陈', '刘', '杨', '黄', '周', '吴', '徐', '孙', '马', '朱']
  const boyNames = ['伟', '强', '磊', '洋', '勇', '军', '杰', '涛', '明', '超']
  const girlNames = ['芳', '娜', '秀英', '敏', '静', '娟', '霞', '艳', '丽', '婷']
  
  for (let i = 0; i < count; i++) {
    const studentId = `2024${classId}${String(i + 1).padStart(3, '0')}`
    const gender = parseInt(studentId) % 2 === 0 ? '男' : '女'
    const surname = surnames[Math.floor(Math.random() * surnames.length)]
    const name = gender === '男' 
      ? boyNames[Math.floor(Math.random() * boyNames.length)]
      : girlNames[Math.floor(Math.random() * girlNames.length)]
    
    students.push({
      id: studentId,
      name: surname + name,
      gender: gender,
      rank: Math.floor(Math.random() * 30) + 1,
      attendance: Math.floor(Math.random() * 20) + 80
    })
  }
  
  return students
}

export default router 